/**
 * Filename: SettingActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/9 2:36
 */
package com.github.postsanf.yinian.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNComment;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNCommentResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.widget.TipEditText;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.LinkedHashMap;

public class TimeKeyWordActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_write_complete;
    private TextView tv_write_cancel;
    private InputMethodManager imm;
    private LinearLayout buttom;
    private TipEditText et_write_word;
    private boolean text_content = false;
    private YNStatus mCurStatus;
    private YNUser sys = new YNUser();
    private YNUser commentedUser;
    private String cContent;
    private boolean isSending = false;                  //  是否在发布评论  默认 否
    // 状态栏的高度
    private int statusBarHeight;
    // 软键盘的高度
    private int keyboardHeight;
    // 软键盘的显示状态
    private boolean isShowKeyboard;
    private RelativeLayout layout_main;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.yn_timekey_word);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initDatas();
        initView();
        statusBarHeight = getStatusBarHeight(getApplicationContext());
        layout_main = (RelativeLayout) findViewById(R.id.layout_main);
//        layout_main.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
        doComment();
//        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//        SoftKeyboardUtil.observeSoftKeyboard(this, new SoftKeyboardUtil.OnSoftKeyboardChangeListener() {
//            @Override
//            public void onSoftKeyBoardChange(int softKeybardHeight, boolean visible) {
//                Log.i("xjs","softKeybardHeight===》"+softKeybardHeight);
//                if (visible) {
//                    buttom.setVisibility(View.VISIBLE);
//                }
//            }
//        });

    }


    private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // 应用可以显示的区域。此处包括应用占用的区域，
            // 以及ActionBar和状态栏，但不含设备底部的虚拟按键。
            Rect r = new Rect();
            layout_main.getWindowVisibleDisplayFrame(r);
            // 屏幕高度。这个高度不含虚拟按键的高度
            int screenHeight = layout_main.getRootView().getHeight();

            int heightDiff = screenHeight - (r.bottom - r.top);

            // 在不显示软键盘时，heightDiff等于状态栏的高度
            // 在显示软键盘时，heightDiff会变大，等于软键盘加状态栏的高度。
            // 所以heightDiff大于状态栏高度时表示软键盘出现了，
            // 这时可算出软键盘的高度，即heightDiff减去状态栏的高度
            if (keyboardHeight == 0 && heightDiff > statusBarHeight) {
                keyboardHeight = heightDiff - statusBarHeight;
            }

            if (isShowKeyboard) {
                // 如果软键盘是弹出的状态，并且heightDiff小于等于状态栏高度，
                // 说明这时软键盘已经收起
                if (heightDiff <= statusBarHeight) {
                    isShowKeyboard = false;
//                    onHideKeyboard();
                }
            } else {
                // 如果软键盘是收起的状态，并且heightDiff大于状态栏高度，
                // 说明这时软键盘已经弹出
                if (heightDiff > statusBarHeight) {
                    isShowKeyboard = true;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            buttom.setVisibility(View.VISIBLE);
                        }
                    }, 1000);
//                    onShowKeyboard();
                }
            }
        }
    };


    public int getStatusBarHeight(Context context) {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    private void initView() {
        buttom = (LinearLayout) findViewById(R.id.buttom);
        et_write_word = (TipEditText) findViewById(R.id.et_write_word);
        tv_write_complete = (TextView) findViewById(R.id.tv_write_complete);
        tv_write_cancel = (TextView) findViewById(R.id.tv_write_cancel);
        findViewById(R.id.timecard_from_enty_scroll).setOnClickListener(this);
        tv_write_complete.setOnClickListener(this);
        tv_write_cancel.setOnClickListener(this);
        text_content = getIntent().getBooleanExtra("text_content", false);
        if (text_content) {
            commentedUser = (YNUser) getIntent().getSerializableExtra("cynuser");
            et_write_word.setHint("//回复" + commentedUser.getUnickname() + ":");
        }
    }

    private void initDatas() {
        mCurStatus = YNSingleton.getInstance().getCurStatus();
        sys.setUserid(CommonConstants.SYSTEM_ID);
        commentedUser = sys;
    }

    private void doComment() {
        if (checkComment() && !isSending) {
            isSending = true;       // 更改状态
            LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
            mParam.put(CommonConstants.YNS_COMMENT_USER_ID, String.valueOf(application.getCurID()));
            mParam.put(CommonConstants.YNS_COMMENTED_USER_ID, String.valueOf(commentedUser.getUserid()));
            mParam.put(CommonConstants.YNS_EVENT_ID, String.valueOf(mCurStatus.getEid()));
            mParam.put(CommonConstants.YNS_PLACE, MainActivity.LocationCity);
            mParam.put(CommonConstants.YNS_CONTENT, cContent);
            Log.i("xjs", "mps" + mParam.toString());
            StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynSendComment)).setMethod(HttpMethods.Post).setParamMap(mParam)
                    .setHttpListener(new HttpListener<String>(true, false, true) {
                        @Override
                        public void onSuccess(String s, Response<String> response) {
                            Log.i("xjs", "usss==>" + s);
                            YNCommentResponse resSendComment = gson.fromJson(s, YNCommentResponse.class);
                            if (resSendComment != null && ReqUtils.isSuccess(resSendComment.getCode())) {
                                YNComment createComment = resSendComment.getData().get(0);
                                createComment.setCplace(MainActivity.LocationCity);
                                createComment.setCcontent(cContent);
                                application.getCurUser().setUserid(application.getCurID());
                                createComment.setCommentUser(application.getCurUser());
                                createComment.setCommentedUser(commentedUser);
                                createComment.setCtime(DateFormat.format("yyyy-MM-dd  HH:mm:ss", new Date()).toString());
                                mCurStatus.getComments().add(mCurStatus.getComments().size(), createComment);
//                                mAdapter.notifyItemInserted(mCurStatus.getComments().size());
//                                mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
                                // 通知评论更新
                                sendBroadcast(new Intent(ACTIONs.actionComment));
                                et_write_word.setHint("发表评论");
                                et_write_word.setText("");
                                // 还原当前对系统的评论
                                commentedUser = sys;
                            } else {
                                showToast(resSendComment.getMsg());
                            }
                            // 还原状态
                            isSending = false;
                        }

                        @Override
                        public void onFailure(HttpException e, Response<String> response) {
                            showToast(CommonConstants.YN_NET_LINK);
                            // 还原状态
                            isSending = false;
                        }
                    });
            liteHttp.executeAsync(req);
        }
    }

    // 检测评论
    private Boolean checkComment() {
        cContent = et_write_word.getText().toString().trim();
        if (StringUtils.isEmptyString(cContent)) {
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_write_complete:
                doComment();
                imm.hideSoftInputFromWindow(et_write_word.getWindowToken(), 0);
                finish();
                break;
            case R.id.tv_write_cancel:
                imm.hideSoftInputFromWindow(et_write_word.getWindowToken(), 0);
                finish();
                break;
            case R.id.timecard_from_enty_scroll:
                imm.hideSoftInputFromWindow(et_write_word.getWindowToken(), 0);
                finish();
                break;
        }
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
